//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/10/2.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit
import AFNetworking


private let WBErrorDomain = "com.baidu.data.error"
private let API_ROOT_URL = "https://api.weibo.com/"
//private let API_ROOT_URL = "https://192.168.10.25:8080"

enum HTTPMethod: String {
    case POST = "POST"
    case GET = "GET"
}



class NetworkTools: AFHTTPSessionManager {
    
    let WB_Client_Id = "315779718"
    let WB_Redirect_Uri = "http://www.itcast.cn"
    let WB_Client_Secret = "ed07732b25cde6a688c579b758898e7d"
    
    
    static let sharedTools: NetworkTools = {
        let instance = NetworkTools(baseURL: NSURL(string:API_ROOT_URL))
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    var oauthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        return NSURL(string: urlString)!
    }
    
    

    func loadAccessToken(code: String,completion:(dict: [String : AnyObject]?,error: NSError?) -> ()) {
        
        let urlString = "oauth2/access_token"
        
        let parmas = ["client_id":WB_Client_Id,
            "client_secret":WB_Client_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_Uri,
        ]
        
//        responseSerializer = AFHTTPResponseSerializer()
//        self.POST(urlString, parameters: parmas, success: { (_, result) -> Void in
//            let string = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            print(string)
//            }) { (_, error) -> Void in
//        
//        print(error)
        self.requestJSON(.POST, urlString: urlString, parameters: parmas, completion: completion)
    }
    
    //加载用户信息
    func loadUserInfo(uid: String,access_token: String,completion:(dict: [String : AnyObject]?,error: NSError?) -> ()) {
        let urlString = "2/users/show.json"
        let params = ["uid":uid,"access_token":access_token]
        requestJSON(.GET, urlString: urlString, parameters: params, completion: completion)
    }
    
    
    func loadStatus(completion:(dict: [String : AnyObject]?,error: NSError?) -> ()){
        let urlString = "2/statuses/home_timeline.json"
        let params = ["uid":UserAccount.shareUserAccount!.uid!,"access_token":UserAccount.shareUserAccount!.access_token!]
        requestJSON(.GET, urlString: urlString, parameters: params, completion: completion)
    }
    
    
    func requestJSON(method:HTTPMethod, urlString: String, parameters: [String : AnyObject]? = nil,completion:(dict: [String : AnyObject]?,error: NSError?) -> ()) {
        
        let successCallBack = { (tast:NSURLSessionDataTask, result:AnyObject)  in
            if let dict = result as? [String : AnyObject] {
                completion(dict: dict, error: nil)
            } else {
                print("数据不合法")
                completion(dict: nil, error: NSError(domain:WBErrorDomain, code: -1, userInfo: ["error" : "数据不合法"]))
            }
            
        }
        
        let failureCallBack = { (tast:NSURLSessionDataTask,error: NSError)  in
            print(error)
            completion(dict: nil, error: error)
        }
        if method == HTTPMethod.GET {
            self.GET(urlString, parameters: parameters, success: successCallBack, failure: failureCallBack)
        } else if method == HTTPMethod.POST {
            self.POST(urlString, parameters: parameters, success: successCallBack, failure: failureCallBack)
        }
    }
    
}
